"""
工作流管理器 - 统一管理Agent和工作流执行顺序
"""
import asyncio
from typing import Dict, Any, Optional
from workflow.ReportAnalysisWorkflow import ReportAnalysisWorkflow


class WorkflowManager:
    """工作流管理器 - 单例模式"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.workflows = {}
            self._initialized = True
    
    async def get_report_workflow(self, api_key: str = None, base_url: str = None) -> ReportAnalysisWorkflow:
        """获取报表分析工作流实例（单例）"""
        workflow_key = "report_analysis"
        
        if workflow_key not in self.workflows:
            workflow = ReportAnalysisWorkflow(api_key=api_key, base_url=base_url)
            await workflow.initialize()
            self.workflows[workflow_key] = workflow
            print(f"创建新的工作流实例: {workflow_key}")
        
        return self.workflows[workflow_key]
    
    async def execute_report_analysis(self, user_query: str, api_key: str = None, base_url: str = None) -> Dict[str, Any]:
        """执行报表分析工作流"""
        workflow = await self.get_report_workflow(api_key, base_url)
        return await workflow.analyze_report_data(user_query)
    
    async def execute_report_analysis_stream(self, user_query: str, api_key: str = None, base_url: str = None):
        """执行报表分析工作流（流式）"""
        workflow = await self.get_report_workflow(api_key, base_url)
        async for result in workflow.analyze_report_data_stream(user_query):
            yield result
    
    def get_workflow_info(self) -> Dict[str, Any]:
        """获取工作流信息"""
        return {
            "available_workflows": list(self.workflows.keys()),
            "workflow_count": len(self.workflows),
            "status": "initialized" if self._initialized else "not_initialized"
        }


# 全局单例实例
workflow_manager = WorkflowManager()